import React, { useState, useEffect } from 'react';
import SearchList from '@/components/SearchList';
import { Table, Button, notification, Tooltip } from 'antd';
import {
  PlusCircleFilled,
  EyeFilled,
  EditFilled,
  DeleteFilled,
  SnippetsFilled,
} from '@ant-design/icons';
import {
  transFormIndex,
  reportStatusMap,
  showDeleteConfirm,
} from '@/utils/util';
import API from '@/api/xjindex.js';
import { useModel } from 'umi';

// 工作部署
const workDeployment = ({ history }) => {
  const { initialState } = useModel('@@initialState');
  const { orgId, orgName, userId } = initialState.info;
  const [receiverList, setreceiverList] = useState([]);
  const [JSDW] = useState([]);
  const [JJCD, setJJCD] = useState([]);
  const _JJCD = {};
  const [dataSource, setDataSource] = useState([]);
  const [params, setParams] = useState({
    receiverId: '',
    workName: '',
    emergency: '-1',
    notificationTime: '',
  });
  const [pagination, setPagination] = useState({
    pageSize: 10, //每条的页数
    current: 1,
    showQuickJumper: true,
  });
  const searchList = [
    {
      name: 'workName',
      title: '工作名称',
      type: 'input',
    },
    {
      name: 'receiverId',
      title: '接收单位',
      type: 'select',
      otherProps: {
        options: receiverList,
      },
    },
    {
      name: 'emergency',
      title: '紧急程度',
      type: 'select',
      otherProps: {
        options: JJCD,
      },
    },
    {
      name: 'notificationTime',
      title: '部署时间',
      type: 'datepicker',
    },
  ];

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      render: (text, r, index) => transFormIndex(pagination, index),
    },
    {
      title: '工作名称',
      dataIndex: 'workName',
      align: 'center',
    },
    {
      title: '紧急程度',
      dataIndex: 'emergency',
      align: 'center',
    },
    {
      title: '接收单位',
      dataIndex: 'receiverName',
      ellipsis: true,
      align: 'center',
    },
    {
      title: '部署时间',
      dataIndex: 'notificationTime',
      align: 'center',
    },
    {
      title: '通报状态',
      dataIndex: 'reportState',
      render: (text) => reportStatusMap(text),
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'Operation',
      align: 'center',
      render: (text, r) => (
        <div>
          <Tooltip title="查看">
            <Button
              type="link"
              icon={<EyeFilled />}
              className="table-icon"
              onClick={checkLink.bind(null, r.id)}
            ></Button>
          </Tooltip>
          {(orgId == '101' && r.userId == userId && r.reportState == 0) ||
          (orgId != '101' && r.disposeState == 0) ? (
            <Tooltip title={orgId == '101' ? '编辑' : '处置'}>
              <Button
                type="link"
                icon={orgId == '101' ? <EditFilled /> : <SnippetsFilled />}
                className="table-icon"
                onClick={editLink.bind(null, r)}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
          {r.reportState == 0 && r.userId == userId ? (
            <Tooltip title="删除">
              <Button
                type="link"
                icon={<DeleteFilled />}
                className="table-icon"
                onClick={() => showDeleteConfirm(() => delFn(r.id))}
              ></Button>
            </Tooltip>
          ) : (
            ''
          )}
        </div>
      ),
    },
  ];
  const pageSizeChange = (page) => {
    initList({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
    });
    setParams({
      ...params,
      pageNo: page.current,
      pageSize: page.pageSize,
    });
  };

  const createLink = () => {
    history.push('/networkInfor/workDeployment/create');
  };
  const checkLink = (id) => {
    if (orgId == '101') {
      history.push({
        pathname: '/networkInfor/workDeployment/check',
        query: { id },
      });
    } else {
      const params = JSON.stringify({ id: id, receiverId: orgId });
      history.push({
        pathname: '/networkInfor/workDeployment/unit_check',
        query: { params },
      });
    }
  };
  const editLink = (r) => {
    if (orgId == '101') {
      const params = JSON.stringify({ id: r.id, receiverId: r.receiverId });
      history.push({
        pathname: '/networkInfor/workDeployment/edit',
        query: { params },
      });
    } else {
      const id = r.id;
      history.push({
        pathname: '/networkInfor/workDeployment/unit_edit',
        query: { id },
      });
    }
  };

  const delFn = (id) => {
    API.delWork({ id: id }).then((res) => {
      if (res) {
        notification.success({
          message: '删除成功',
        });
        initList(params);
      }
    });
  };
  const changeParams = (data) => {
    setParams({
      ...data,
      pageSize: 10,
      pageNo: 1,
    });
  };
  function initList(params = {}) {
    const dd = {
      receiverId: '',
      workName: '',
      emergency: '-1',
      notificationTime: '',
    };
    if (params.receiverId) {
      params.receiverId = '' + params.receiverId;
    }
    for (let p in dd) {
      //参数为空时设置为-1
      if (params[p] == undefined) {
        params[p] = dd[p];
      }
    }

    if (params && params.notificationTime) {
      //修改时间参数的格式
      params.notificationTime = params.notificationTime.format('YYYY-MM-DD');
    }
    if (orgId == '101') {
      API.showServiceProviderList().then((res) => {
        if (res) {
          res.t.map((item) => {
            JSDW[item.id] = item.name;
          });
          setreceiverList(
            res.t.map((item) => ({ label: item.name, value: item.id })),
          );
        }
      });
    } else {
      setreceiverList([
        {
          label: orgName,
          value: orgId,
        },
      ]);
    }

    API.dictItemList()
      .then((res) => {
        if (res) {
          const JJCDList = [];
          res.t.map((item) => {
            if (item.dictCode == 'JJCD') {
              _JJCD[item.dictItemType] = item.dictItemName;
              JJCDList.push({
                //下拉框
                label: item.dictItemName,
                value: item.dictItemType,
              });
            }
          });
          setJJCD(JJCDList);
        }
      })
      .then(() => {
        API.getWork(params).then((res) => {
          if (res) {
            setDataSource(
              res.t.queryList.map((item) => {
                return {
                  ...item,
                  emergency: _JJCD[item.emergency],
                };
              }),
            );
            setPagination({
              showQuickJumper: true,
              current: res.t.currentPage,
              pageSize: res.t.pageSize,
              total: res.t.totalSize,
            });
          }
        });
      });
  }
  useEffect(() => {
    initList(params);
  }, [params]);
  return (
    <>
      <SearchList searchList={searchList} initList={changeParams}></SearchList>
      <div className="main-x bgf">
        {orgId == '101' ? (
          <div className="tools-x">
            <Button
              type="link"
              icon={<PlusCircleFilled />}
              className="btn-icon"
              onClick={createLink}
            >
              新增
            </Button>
          </div>
        ) : (
          ''
        )}
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          pagination={pagination}
          className={'custom-table'}
          onChange={pageSizeChange}
        ></Table>
      </div>
    </>
  );
};

export default workDeployment;
